﻿﻿import plugin from "../../lib/plugins/plugin.js";
import common from "../../lib/common/common.js";
import moment from 'moment'
import fetch from "node-fetch";
import fs from "fs"
import yaml from "yaml"
import pLimit from 'p-limit'

let maxnum = 30  //并发限制

let daili = 'i.yuki.sh'
let size = 'large'  //large（一般）, original（原图）

let wang = ''
let day = 'month'
let aiset = true

let cooldowns = new Map();
let NumReg = '[一壹二两三四五六七八九十百千万亿\\d]+'
//1.定义命令规则
export class example extends plugin {
  constructor() {
    super({
      /** 功能名称 */
      name: 'hibiapi',
      /** 功能描述 */
      dsc: '简单开发示例',
      /** https://oicqjs.github.io/oicq/#events */
      event: 'message',
      /** 优先级，数字越小等级越高 */
      priority: 6,
      rule: [
		{
          reg: '^#?piv搜图(.*)$', //匹配消息正则,命令正则
          fnc: 'hibi'
        },
		{
          reg: '^#?piv搜(画师|作者)(.*)$', //匹配消息正则,命令正则
          fnc: 'hibiuser'
        },
		{
          reg: '^#?piv看(.*)$', //匹配消息正则,命令正则
          fnc: 'hibirank'
        },
        {
          reg: '^#?piv搜id(链接)?(.*)$|#?pid搜图(链接)?(.*)$', //匹配消息正则,命令正则
          fnc: 'hibipid'
        },
		{
          reg: '^#时段类型(.*)$', //匹配消息正则,命令正则
          fnc: 'hibiday'
        }
      ]
    })
  }


async hibiday(e) {
	if (!e.isMaster) {
	 return;
    }
	let groupId = e.group_id;
	let msg = e.msg.replace(/#时段类型/g, '').trim()
    if (msg == 'day') {
		day = 'day' 
		e.reply(`day ok`)
    }
	else if (msg == 'week') {
	    day = 'week' 
		e.reply(`week ok`)
		}
	else if (msg == 'month') {
		day = 'month' 
		e.reply(`month ok`)
		}
    else if (e.msg == '#piv图片模式') {
		day = 'month' 
		e.reply(`month ok`)
		}	
    else if (e.msg == 'month') {
		day = 'month' 
		e.reply(`month ok`)
		}			
	else { 
	  e.reply(`时段类型只能为 day, week, month`)
	  }
  }
 
 
  async hibi(e) {
	if (!e.isGroup) {
	    return;
    }
	if (!wang) return e.reply('请先设置hibiapi地址', true)
		
	let groupId = e.group_id
    let cfg = await loadcfg(groupId)
	if (!cfg && !e.isMaster) return

    if (!cfg.setu && !e.isMaster) {
	 logger.mark(`${groupId} 涩图权限 ${cfg.setu}`)
     return;
    }
    if (!e.isMaster ) {
	    let cooldown = cooldowns[groupId];
	    if (cooldown && cooldown > Date.now()) {
            let remainingTime = Math.ceil((cooldown - Date.now()) / 1000);
            e.reply(`lsp注意身体，请${remainingTime}秒后再来～`,false,{ recallMsg: 5 });
            return;
        }
	}	
	
	  let key = e.msg.replace(/#|piv搜图/g, '').trim()
      let pageMatch = e.msg.match(new RegExp(`第(${NumReg})页`));
	  let page = 1;
      if (pageMatch) {
          page = Number(pageMatch[1]);
      if (isNaN(page)) {
          e.reply('请输入阿拉伯数字');
          return;
          }
        key = key.replace(pageMatch[0], "").trim();  // 去掉匹配的页码部分
      }

      let url = `${wang}/api/pixiv/search?word=${key}&mode=partial_match_for_tags&order=date_desc&duration=within_last_${day}&include_translated_tag_results=true&page=${page}&size=30&search_ai_type=${aiset}`;
	  let url2 = `${wang}/api/pixiv/search?word=${key}&mode=partial_match_for_tags&order=date_desc&duration=within_last_${day}&include_translated_tag_results=false&page=${page}&size=30&search_ai_type=${aiset}`;
	  let response = ""
	  let res = ""
	     try{
                response = await fetch(url);
                res = await response.json();
			} catch (error) {
			    e.reply('请求失败')
				return
			}
	if (res.error) {
		logger.mark('尝试方式2')
            response = await fetch(url2);
            res = await response.json();
	}	
    if (res.error || !res.illusts || res.illusts == "") {
		e.reply(`没有相关结果`,false,{ recallMsg: 5 })
		return
	}	
	// 只有在请求成功时才设置CD
    if (!e.isMaster) {
        cooldowns[groupId] = Date.now() + cfg.cd * 1000;
    }

	e.reply(`开始执行任务 搜图${key}[${page}]，速度较慢请耐心等待...`,false,{ recallMsg: 5 })
	
    let msgs = [e.msg]
	let msgsr = [`${e.msg}（非全年龄内容）`]
    // 设置并发限制
    const limit = pLimit(maxnum)
	
    await Promise.all(res.illusts.map((k, index) => limit(async () => {
        const { 
            title, id, user, create_date, illust_ai_type, x_restrict,
            tags, meta_single_page, meta_pages, image_urls 
        } = k;

        // 生成基本信息
        const tagStr = tags.map(t => `${t.name}(${t.translated_name})`).join('，');
        const info = `【标题】${title}\n【日期】${moment(create_date).format('YYYY-MM-DD HH:mm:ss')}\n【pid】${id}\n【画师】${user.name} (id: ${user.id})\n【isAI】${illust_ai_type == 2}\n【全年龄】${x_restrict == 0}\n【tags】${tagStr}`;

        // 处理图片URL（统一代理替换）
        const getImageUrls = async() => {
			let urls = []
            if (meta_single_page.original_image_url) {
				let img_url = size == 'original' ? meta_single_page.original_image_url : image_urls.large
                    img_url = img_url.replace('i.pximg.net', daili)
				    x_restrict == 1 ? urls.push(await shorturl(img_url)) : urls.push(img_url)
            }
            if (meta_pages?.length > 0) {
                for (let meta of meta_pages) {
                    let processedUrl = meta.image_urls[size].replace('i.pximg.net', daili);
                    x_restrict == 1 ? urls.push(await shorturl(processedUrl)) : urls.push(processedUrl)
                }
            }
            return urls
        };
        
        // 根据x_restrict分类处理
		const imageUrls = await getImageUrls();
        x_restrict === 1 
            ? msgsr.push(info, ...imageUrls)
            : msgs.push([info, ...imageUrls.map(url => segment.image(url))]);
    })));

    if (msgs.length > 1) await e.reply(await common.makeForwardMsg(e,msgs),false,{ recallMsg: cfg.recall });
	if (msgsr.length > 1) await e.reply(await common.makeForwardMsg(e,msgsr),false,{ recallMsg: cfg.recall });

	 return true	
	 
    }

  async hibiuser(e) {
	if (!e.isGroup) {
	    return;
    }
	if (!wang) return e.reply('请先设置hibiapi地址', true)
		
	let groupId = e.group_id
    let cfg = await loadcfg(groupId)
	if (!cfg && !e.isMaster) return

    if (!cfg.setu && !e.isMaster) {
	 logger.mark(`${groupId} 涩图权限 ${cfg.setu}`)
     return;
    }
    if (!e.isMaster ) {
	    let cooldown = cooldowns[groupId];
	    if (cooldown && cooldown > Date.now()) {
            let remainingTime = Math.ceil((cooldown - Date.now()) / 1000);
            e.reply(`lsp注意身体，请${remainingTime}秒后再来～`,false,{ recallMsg: 5 });
            return;
        }
	}	
	
	  let key = e.msg.replace(/#|piv搜(画师|作者)/g, '').trim()
      let url = `${wang}/api/pixiv/search_user?word=${key}`;
	  let response = ""
	  let res = ""
	     try{
                response = await fetch(url);
                res = await response.json();
			} catch (error) {
			    e.reply('请求失败')
				return
			}
    if (res.user_previews == "") {
		e.reply(`没有相关结果`,false,{ recallMsg: 5 })
		return
	}
	if (!res.user_previews[0].illusts) {
		e.reply(`没有相关结果`,false,{ recallMsg: 5 })
		return
	}
	// 只有在请求成功时才设置CD
    if (!e.isMaster) {
        cooldowns[groupId] = Date.now() + cfg.cd * 1000;
    }
	
		e.reply(`开始执行任务 搜画师${key}，速度较慢请耐心等待...`,false,{ recallMsg: 5 })
		
        let msgs = [e.msg]

        msgs.push(`${res.user_previews[0].user.name}（${res.user_previews[0].user.id}）\n最新作品如下：`)
	// 设置并发限制
    const limit = pLimit(maxnum)
	
    await Promise.all(res.user_previews[0].illusts.map((k, index) => limit(async () => {
        const { 
            title, id, user, create_date, illust_ai_type, x_restrict,
            tags, meta_single_page, meta_pages, image_urls 
        } = k;

        // 生成基本信息
        const tagStr = tags.map(t => `${t.name}(${t.translated_name})`).join('，');
        const info = `【标题】${title}\n【日期】${moment(create_date).format('YYYY-MM-DD HH:mm:ss')}\n【pid】${id}\n【画师】${user.name} (id: ${user.id})\n【isAI】${illust_ai_type == 2}\n【全年龄】${x_restrict == 0}\n【tags】${tagStr}`;

        // 处理图片URL（统一代理替换）
        const getImageUrls = async() => {
			let urls = []
            if (meta_single_page.original_image_url) {
				let img_url = size == 'original' ? meta_single_page.original_image_url : image_urls.large
                    img_url = img_url.replace('i.pximg.net', daili)
				    x_restrict == 1 ? urls.push(await shorturl(img_url)) : urls.push(img_url)
            }
            if (meta_pages?.length > 0) {
                for (let meta of meta_pages) {
                    let processedUrl = meta.image_urls[size].replace('i.pximg.net', daili);
                    x_restrict == 1 ? urls.push(await shorturl(processedUrl)) : urls.push(processedUrl)
                }
            }
            return urls
        };
        
        // 根据x_restrict分类处理
		const imageUrls = await getImageUrls();
        x_restrict === 1 
            ? msgs.push(info, ...imageUrls)
            : msgs.push([info, ...imageUrls.map(url => segment.image(url))]);
    })));
  
    if (msgs.length > 1) await e.reply(await common.makeForwardMsg(e,msgs),false,{ recallMsg: cfg.recall });

    return true;
	
    }


  async hibirank(e) {
	if (!e.isGroup) {
	    return;
    }
	if (!wang) return e.reply('请先设置hibiapi地址', true)
		
	let groupId = e.group_id
    let cfg = await loadcfg(groupId)
	if (!cfg && !e.isMaster) return

    if (!cfg.setu && !e.isMaster) {
	 logger.mark(`${groupId} 涩图权限 ${cfg.setu}`)
     return;
    }
    if (!e.isMaster ) {
	    let cooldown = cooldowns[groupId];
	    if (cooldown && cooldown > Date.now()) {
            let remainingTime = Math.ceil((cooldown - Date.now()) / 1000);
            e.reply(`lsp注意身体，请${remainingTime}秒后再来～`,false,{ recallMsg: 5 });
            return;
        }
	}	
	
	  let key = e.msg.replace(/#|piv看/g, '').trim()
      let pageMatch = e.msg.match(new RegExp(`第(${NumReg})页`));
	  let page = 1;
      if (pageMatch) {
          page = Number(pageMatch[1]);
      if (isNaN(page)) {
          e.reply('请输入阿拉伯数字');
          return;
          }
        key = key.replace(pageMatch[0], "").trim();  // 去掉匹配的页码部分
      }
	  
    const rankings = {
      '日榜': 'day',
      '周榜': 'week',
      '月榜': 'month',
      '男性向日榜': 'day_male',
      '女性向日榜': 'day_female',
      '原创周榜': 'week_original',
      '新人周榜': 'week_rookie',
      'AI日榜': 'day_ai',
      '漫画日榜': 'day_manga',
      '漫画周榜': 'week_manga',
      '漫画月榜': 'month_manga',
      '漫画新人周榜': 'week_rookie_manga'
    };
    let keyword = rankings[key];
    if (!keyword) {
      e.reply(`日榜，周榜，月榜，男性向，女性向，原创周榜，新人周榜，AI日榜，漫画日榜，漫画周榜，漫画月榜，漫画新人周榜`,false,{ recallMsg: 10 })
	  return
    }
      let url = `${wang}/api/pixiv/rank?mode=${keyword}&page=${page}`;
	  let response = ""
	  let res = ""
	     try{
                response = await fetch(url);
                res = await response.json();
			} catch (error) {
			    e.reply('请求失败')
				return
			}	
    if (res.error || !res.illusts || res.illusts == "") {
		e.reply(`没有相关结果`,false,{ recallMsg: 5 })
		return
	}
	// 只有在请求成功时才设置CD
    if (!e.isMaster) {
        cooldowns[groupId] = Date.now() + cfg.cd * 1000;
    }
	
		e.reply(`开始执行任务 看${key}[${page}]，速度较慢请耐心等待...`,false,{ recallMsg: 5 })
		
        let msgs = [];

        msgs.push(`${e.msg}`)
    // 设置并发限制
    const limit = pLimit(maxnum)
	
    await Promise.all(res.illusts.map((k, index) => limit(async () => {
        const { 
            title, id, user, create_date, illust_ai_type, x_restrict,
            tags, meta_single_page, meta_pages, image_urls 
        } = k;

        // 生成基本信息
        const tagStr = tags.map(t => `${t.name}(${t.translated_name})`).join('，');
        const info = `【标题】${title}\n【日期】${moment(create_date).format('YYYY-MM-DD HH:mm:ss')}\n【pid】${id}\n【画师】${user.name} (id: ${user.id})\n【isAI】${illust_ai_type == 2}\n【全年龄】${x_restrict == 0}\n【tags】${tagStr}`;

        // 处理图片URL（统一代理替换）
       const getImageUrls = async() => {
			let urls = []
            if (meta_single_page.original_image_url) {
				let img_url = size == 'original' ? meta_single_page.original_image_url : image_urls.large
                    img_url = img_url.replace('i.pximg.net', daili)
				    x_restrict == 1 ? urls.push(await shorturl(img_url)) : urls.push(img_url)
            }
            if (meta_pages?.length > 0) {
                for (let meta of meta_pages) {
                    let processedUrl = meta.image_urls[size].replace('i.pximg.net', daili);
                    x_restrict == 1 ? urls.push(await shorturl(processedUrl)) : urls.push(processedUrl)
                }
            }
            return urls
        };
        
        // 根据x_restrict分类处理
		const imageUrls = await getImageUrls();
        x_restrict === 1 
            ? msgs.push(info, ...imageUrls)
            : msgs.push([info, ...imageUrls.map(url => segment.image(url))]);
    })));

	if (msgs.length > 1) await e.reply(await common.makeForwardMsg(e,msgs),false,{ recallMsg: cfg.recall });
	
    return true;
  
    }
	
		
  async hibipid(e) {
	if (!e.isGroup) {
	    return;
    }
	if (!wang) return e.reply('请先设置hibiapi地址', true)
		
	let groupId = e.group_id
    let cfg = await loadcfg(groupId)
	if (!cfg && !e.isMaster) return

    if (!cfg.setu && !e.isMaster) {
	 logger.mark(`${groupId} 涩图权限 ${cfg.setu}`)
     return;
    }
    if (!e.isMaster ) {
	    let cooldown = cooldowns[groupId];
	    if (cooldown && cooldown > Date.now()) {
            let remainingTime = Math.ceil((cooldown - Date.now()) / 1000);
            e.reply(`lsp注意身体，请${remainingTime}秒后再来～`,false,{ recallMsg: 5 });
            return;
        }
	}	
	  let pids = e.msg.replace(/#|(piv搜id|pid搜图)(链接)?/g, '').trim()
	  if (!pids) return
	  let url = `${wang}/api/pixiv/illust?id=${pids}`
	  let response = ""
	  let res = ""
	     try{
                response = await fetch(url);
                res = await response.json();
			} catch (error) {
			    e.reply('请求失败')
				return
			}
    if (res.error || !res.illust || res.illust == "") {
		e.reply(`没有相关结果`,false,{ recallMsg: 5 })
		return
	}
	// 只有在请求成功时才设置CD
    if (!e.isMaster) {
        cooldowns[groupId] = Date.now() + cfg.cd * 1000;
    }

	   e.reply(`开始执行任务 搜id${pids}，速度较慢请耐心等待...`,false,{ recallMsg: 5 })
	
    let msgs = [`${e.msg}`]

        const { 
            title, id, user, create_date, illust_ai_type, x_restrict,
            tags, meta_single_page, meta_pages, image_urls 
        } = res.illust;

        // 生成基本信息
        const tagStr = tags.map(t => `${t.name}(${t.translated_name})`).join('，');
        const info = `【标题】${title}\n【日期】${moment(create_date).format('YYYY-MM-DD HH:mm:ss')}\n【pid】${id}\n【画师】${user.name} (id: ${user.id})\n【isAI】${illust_ai_type == 2}\n【全年龄】${x_restrict == 0}\n【tags】${tagStr}`;

        // 处理图片URL（统一代理替换）
        const getImageUrls = async() => {
			let urls = []
            if (meta_single_page.original_image_url) {
				let img_url = meta_single_page.original_image_url.replace('i.pximg.net', daili)
				    x_restrict == 1 ? urls.push(await shorturl(img_url)) : urls.push(img_url)
            }
            if (meta_pages?.length > 0) {
                for (let meta of meta_pages) {
                    let processedUrl = meta.image_urls.original.replace('i.pximg.net', daili);
                    x_restrict == 1 ? urls.push(await shorturl(processedUrl)) : urls.push(processedUrl)
                }
            }
            return urls
        };
        
        // 根据x_restrict分类处理
		const imageUrls = await getImageUrls();
        x_restrict === 1 
            ? msgs.push(info, ...imageUrls)
            : msgs.push([info, ...imageUrls.map(url => segment.image(url))]);
	
	if (msgs.length > 1) await e.reply(await common.makeForwardMsg(e,msgs),false,{ recallMsg: cfg.recall });

    return true;

  }

}

async function shorturl(url) {
	try {
        let res = await fetch(`http://api.yuyula.art/shorten?url=${url}`);
	    let data = await res.json()
		return data.short_url
	} catch(error) {
        return url
	}
}

async function loadcfg(id) {
	let file = `data/pixiv.yaml`
    if (!fs.existsSync(file)) return false
	
    let data = yaml.parse(fs.readFileSync(file, 'utf8'))
	if (!data[id]) return false
	
	return data[id]
}




